<?php
declare(strict_types=1);

namespace App\Controller;

use App\Model\UsersModel;
use Hyperf\Di\Annotation\Inject;
use Phper666\JwtAuth\Jwt;
use Server\formUser;
use Server\MessageTypes;
use Server\RoomTipTypes;

class AuthController extends AbstractController
{
    /**
     * @Inject
     *
     * @var Jwt
     */
    protected $jwt;

    /**
     * 用户登录.
     *
     * @return array
     */
    public function login()
    {
        $message = new \Server\message();
        $message->setType(MessageTypes::System);
        $message->setForm(new formUser([
            'id' => 1,
            'nickname' => '123333',
        ]));
        $message->setValue('123');
        $message->setRoomTipType(RoomTipTypes::createRoomSuccess);
        try {
            $user = UsersModel::query()
                ->where('mobile', $this->request->input('mobile'))
                ->first();
            //验证用户账户密码
            if ($user) {
                $userData = [
                    'id' => $user->id,
                    'mobile' => $user->mobile,
                    'nickname' => $user->nickname,
                ];
                $token = $this->jwt->getToken($userData);
                $data = [
                    'token' => (string)$token,
                    'exp' => $this->jwt->getTTL(),
                ];
                return $this->success($data,$message->serializeToJsonString());
            }

            throw new \Exception('账号或密码错误');
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }

    }

    /**
     * 获取用户信息
     * @return [type] [description]
     */
    public function info()
    {
        //获取用户数据
        try {
            $user = $this->request->getAttribute('user');
            return $this->success($user);
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }

    }

    /**
     * 用户退出
     * @return array [type] [description]
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function logout()
    {
        if ($this->jwt->logout()) {
            return $this->success('', '退出登录成功');
        };
        return $this->failed('退出登录失败');
    }

}

